package nciae.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import nciae.db.common.CommonResult;
import nciae.db.mapper.*;
import nciae.db.pojo.dto.ApiLogDTO;
import nciae.db.pojo.dto.LogDato;
import nciae.db.pojo.entity.*;
import nciae.db.pojo.entity.Classs;
import nciae.db.pojo.vo.LogVo;
import nciae.db.pojo.vo.LogVoId;
import nciae.db.service.ILogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import nciae.db.utils.FileUploadUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static nciae.db.utils.FileUploadUtils.FILE_PATH;

/**
 * <p>
 *  日志管理
 * </p>
 *
 * @author author
 * @since 2024-12-12
 */
@Slf4j
@Component
@Service
public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements ILogService {


    @Autowired
    private LogMapper mapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    ClassMapper classMapper;


    //通过id查询用户，回显from表单  数据的回显
    @Override
    public LogVoId logInfo(Long id) {
        try {
            Log log = mapper.selectById(id);
            Long userId = log.getUserId();
            Long projectId = log.getProjectId();
            LocalDateTime logDate = log.getLogDate();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String date = logDate.format(formatter);
            System.out.println(date);
            LogVoId logVoid = new LogVoId();
            BeanUtils.copyProperties(log, logVoid);
            Student student = studentMapper.selectById(userId);
            logVoid.setUserId(Long.valueOf(student.getId()));

            logVoid.setName(student.getName());
            logVoid.setProjectName(projectMapper.selectById(log.getProjectId()).getProjectName());
            logVoid.setClassName(classMapper.selectById(student.getClassId()).getClassName());
            logVoid.setFileUrls(getDiaryDetailFileNames(log, userId, projectId,date));
            logVoid.setImgUrls(getImageFileNames(log.getUrlImg(), userId, projectId,date));
            return logVoid;

        }catch (Exception e){
            return null;
        }

    }

    private List<String> getImageFileNames(String urlFile, Long userId, Long projectId,String date) {
        List<String> fileNames = new ArrayList<>();
        // 指定要查询的路径
        String path = urlFile;
        if(path == null){
            return fileNames;
        }
        File directory = new File(path);

        // 检查路径是否存在且为目录
        if (directory.exists() && directory.isDirectory()) {
            // 获取目录下的所有文件和文件夹
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    // 打印文件名
                    fileNames.add(FileUploadUtils.FILE_URL+ "DiaryFiles/" + String.valueOf(userId) + "/" + String.valueOf(projectId) + "/" + date + "/"+"img/"+ file.getName());
                }
            }
        }
        return fileNames;
    }

    private List<String> getDiaryDetailFileNames(Log log, Long StudentId, Long projectId, String date) {
        String urlFile = log.getUrlFile();
        return getFileNames(urlFile, StudentId, projectId,date);
    }
    private List<String> getFileNames(String url_file, Long StudentId, Long projectId,String date) {
        List<String> fileNames = new ArrayList<>();
        // 指定要查询的路径
        String path = url_file;
        if(path == null){
            return fileNames;
        }
        File directory = new File(path);

        // 检查路径是否存在且为目录
        if (directory.exists() && directory.isDirectory()) {
            // 获取目录下的所有文件和文件夹
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    // 打印文件名
                    fileNames.add(FileUploadUtils.FILE_URL+ "DiaryFiles/" + String.valueOf(StudentId) + "/" + String.valueOf(projectId) + "/" +date+"/"+ "file/"+ file.getName());
                }
            }
        }
        return fileNames;
    }

    @Override
    public CommonResult<Boolean> ApilogInsert(ApiLogDTO apiLogDTO) {
        CommonResult<Boolean> result = new CommonResult<>();
        try{
            Long userId = apiLogDTO.getUserId();
            Long projectId = apiLogDTO.getProjectId();
            QueryWrapper<Log> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId).eq("project_id", projectId);
            Log log = mapper.selectOne(wrapper);
            int insert = 0;
            if(log != null){
                String diaryContent = apiLogDTO.getContent();
                log.setUserId(userId);
                log.setProjectId(projectId);
                log.setContent(diaryContent);
                log.setLogDate(LocalDateTime.now());
                log.setSubmitDate(LocalDateTime.now());
                log.setState(0);
                insert = mapper.updateById(log);
            }else{
                Log Insertlog = new Log();
                String diaryContent = apiLogDTO.getContent();
                Insertlog.setUserId(userId);
                Insertlog.setProjectId(projectId);
                Insertlog.setContent(diaryContent);
                Insertlog.setLogDate(LocalDateTime.now());
                Insertlog.setSubmitDate(LocalDateTime.now());
                Insertlog.setState(0);

                insert = mapper.insert(log);
            }

            if(insert > 0){
                result.setCode(0);
                result.setMsg("日志提交成功");
                result.setData(true);
            }
            else {
                result.setCode(-1);
                result.setMsg("日志提交失败");
                result.setData(false);
            }
        }catch (Exception e){
            result.setCode(-1);
            result.setMsg("发生错误"+e.getMessage());
            result.setData(false);
        }
        return result;
    }

    //老师的评阅
    @Override
    public CommonResult logsave(LogDato log, HttpSession session) {

        User user = (User) session.getAttribute("user");
        try {
            QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", log.getId());
            Log selectOne = mapper.selectOne(queryWrapper);
            Boolean result=false;
            CommonResult commonResult=new CommonResult();
            if (selectOne != null) {
                selectOne.setTeacherId(Long.valueOf(user.getId()));
                selectOne.setConfirmDate(LocalDateTime.now());
                selectOne.setState(1);
                selectOne.setAdvice(log.getAdvice());
                selectOne.setScore(log.getScore());
                result = updateById(selectOne);
            }

            if (result) {

                commonResult.setCode(200);
                commonResult.setMsg("日志更新成功");
            }
            else {
                commonResult.setCode(400);
                commonResult.setMsg("没有找到符合条件的日志");
            }
            return commonResult;
        }catch (Exception e){
            CommonResult commonResult = new CommonResult();
            commonResult.setCode(500);
            commonResult.setMsg("日志更新失败"+e.getMessage());
            return commonResult;
        }
    }


    //数据的删除
    @Override
    public CommonResult logDelInfo(Long id) {

        CommonResult commonResult=new CommonResult();
        try {
            if(this.removeById(id)) {
                commonResult.setCode(200);
                commonResult.setMsg("信息删除成功");
            }
            else {
                commonResult.setCode(400);
                commonResult.setMsg("没有找到删除的信息");
            }
            return commonResult;
        }catch (Exception e){
            commonResult.setCode(500);
            commonResult.setMsg("日志删除失败"+e.getMessage());
            return commonResult;
        }
    }


    @Override
    public CommonResult<List<LogVo>> searchInfoAll(int page, int limit, Integer state, String logDate, String projectName, String className, String name,HttpSession session) {
        CommonResult<List<LogVo>> result = new CommonResult<>();
        User user = (User) session.getAttribute("user");
        System.out.println(className);


        try {
            Page<Log> pg = new Page<>(page, limit);
            QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
            QueryWrapper<Student> studentQuery = new QueryWrapper<>();


            if(user.getRole().equals("班主任")){
                Integer userId  = user.getId();
                List<Classs> classs = classMapper.selectList(new QueryWrapper<Classs>().eq("charger_id", userId));
                if (!classs.isEmpty()) {
                    List<Integer> ClassIds = classs.stream()
                            .map(Classs::getId)
                            .collect(Collectors.toList());
                    studentQuery.in("class_id", ClassIds);
                } else {
                    return createEmptyResult();
                }
            }

            // 添加状态查询条件
            if (state != null) {
                queryWrapper.eq("state", state);
            }

            // 添加日期查询条件
            if (logDate != null && !logDate.isEmpty()) {
                queryWrapper.apply("DATE(log_date) = {0}", logDate);
            }

            // 处理用户名、项目名和班级名查询
            if (name != null && !name.isEmpty() || projectName != null && !projectName.isEmpty() || className != null && !className.isEmpty()) {


                // 添加项目名查询条件
                if (projectName != null && !projectName.isEmpty()) {
                    Project project = projectMapper.selectOne(new QueryWrapper<Project>()
                            .eq("project_name", projectName));
                    if (project != null) {
                        studentQuery.eq("project_id", project.getId());
                    } else {
                        // 如果找不到项目,返回空结果
                        return createEmptyResult();
                    }
                }

                // 添加班级名查询条件
                if (className != null && !className.isEmpty()) {
                    Classs classs = classMapper.selectOne(new QueryWrapper<Classs>()
                            .eq("class_name",className));
                    if (classs != null) {
                        studentQuery.eq("class_id",classs.getId());
                    } else {
                        // 如果找不到班级,返回空结果
                        return createEmptyResult();
                    }
                }

                // 添加用户名查询条件
                if (name != null && !name.isEmpty()) {
                    studentQuery.like("name", name);
                }

            }
            // 查询符合条件的学生
            List<Student> students = studentMapper.selectList(studentQuery);
            if (!students.isEmpty()) {
                List<Integer> studentIds = students.stream()
                        .map(Student::getId)
                        .collect(Collectors.toList());
                queryWrapper.in("user_id",studentIds);
            } else {
                return createEmptyResult();
            }

            // 执行分页查询
            mapper.selectPage(pg, queryWrapper);
            List<Log> logs = pg.getRecords();
            List<LogVo> listVo = getLogVos(logs);

            result.setData(listVo);
            result.setCode(0);
            result.setMsg("查询成功");
            result.setCount(pg.getTotal());
            return result;

        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("查询失败：" + e.getMessage());
            return result;
        }
    }

    @Override
    public CommonResult<String> UploadDiaryFiles(MultipartFile file, Long projectId, Long userId,String date) throws IOException {
        CommonResult<String> Fileresult = FileUploadUtils.uploadDiaryFiles(file, userId, projectId,date);
        if(Fileresult.getCode() != 200){
            return Fileresult;
        }

        // 获取上传的文件的磁盘路径
        String deskPath = Fileresult.getData();
        Path path = Paths.get(deskPath);
        System.out.println(deskPath);
        System.out.println(path);

        // 获取文件名
        String fileName = path.getFileName().toString();
        System.out.println(fileName);
        // 获取路径（不包含文件名）
        String filePath = path.getParent().toString();

        // 获取文件的文件名和前端加载路径
        String loadPathOrFileName;
        CommonResult<String> result = new CommonResult<>();
        QueryWrapper<Log> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).eq("project_id",projectId);
        Log log = mapper.selectOne(wrapper);
        int insert = 0;
        if(log == null){
            Log insertLog = new Log();
            insertLog.setUserId(userId);
            insertLog.setProjectId(projectId);
            insertLog.setLogDate(LocalDateTime.now());
            insertLog.setSubmitDate(LocalDateTime.now());
            insertLog.setState(0);
            //如果是图片文件
            if (Objects.requireNonNull(file.getContentType()).startsWith("image/")) {
                insertLog.setUrlImg(filePath);
                loadPathOrFileName =FileUploadUtils.FILE_URL + "DiaryFiles" + "/" + userId  + "/" + projectId + "/" +date + "/"+ "img" + "/" + fileName;
            }else{
                insertLog.setUrlFile(filePath);
                loadPathOrFileName = fileName.substring(fileName.indexOf('_') + 1);
            }
            insert = mapper.insert(insertLog);
        }else{
            log.setUserId(userId);
            log.setProjectId(projectId);
            log.setLogDate(LocalDateTime.now());
            log.setSubmitDate(LocalDateTime.now());
            log.setState(0);
            //如果是图片文件
            if (Objects.requireNonNull(file.getContentType()).startsWith("image/")) {
                log.setUrlImg(filePath);
                loadPathOrFileName =FileUploadUtils.FILE_URL + "DiaryFiles" + "/" + userId  + "/" + projectId + "/" +date + "/"+ "img" + "/" + fileName;
            }else{
                log.setUrlFile(filePath);
                loadPathOrFileName = fileName.substring(fileName.indexOf('_') + 1);
                System.out.println(loadPathOrFileName);
            }
            insert = mapper.update(log,wrapper);
        }
        if(insert > 0){
            result.setCode(200);
            result.setMsg("日志提交成功");
//            Fileresult.setData("日志提交成功");
            result.setData(loadPathOrFileName);
        }
        else {
            result.setCode(500);
            result.setMsg("日志提交失败");
//            Fileresult.setData("日志提交失败");
            return result;
        }
        return result;
    }

    @Override
    public ResponseEntity<Resource> downloadFiles(Integer id) {
        Log log = mapper.selectById(id);
        Long UserId = log.getUserId();
        Student student = studentMapper.selectById(UserId);
        String tel = student.getTel();
        String name = student.getName();
        String urlFile = log.getUrlFile();
        return FileUploadUtils.downloadAllFiles(urlFile, tel+name);
    }

    private CommonResult<List<LogVo>> createEmptyResult() {
        CommonResult<List<LogVo>> result = new CommonResult<>();
        result.setData(new ArrayList<>());
        result.setCode(0);
        result.setMsg("查询成功");
        result.setCount(0);
        return result;
    }



    private List<LogVo> getLogVos(List<Log> list){
        ArrayList<LogVo> logVoList = new ArrayList<>();
        for (Log log:list) {
            logVoList.add(getLogVo(log));
        }
        return logVoList;
    }
    private LogVo getLogVo(Log log) {
        LogVo logVo = new LogVo();
        //自己独有的
        BeanUtils.copyProperties(log,logVo);
        System.out.println(logVo.toString());
        //设置log对应的学员
        Integer studentID = log.getUserId().intValue();
        Student student=studentMapper.selectById(studentID);
        logVo.setName(student.getName());
        logVo.setDepartment(student.getDepartment());
        logVo.setTel(student.getTel());
        //设置项目的名字
        Project project = projectMapper.selectById(student.getProjectId());
        logVo.setProjectName(project.getProjectName());
        //设置班级的名字
        Classs classs= classMapper.selectById(student.getClassId());
        logVo.setClassName(classs.getClassName());
        return logVo;
    }




}
